package com.huang.springboot.controller;

import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

/**
 * @author yili_gi
 */
@Controller
public class UserController {

    @ApiOperation("登陆接口")
    @PostMapping("/login")
    public String login(String username, String password, Model model,HttpSession session){

        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        session.setAttribute("userName",username);
        try {
            subject.login(token);
            return "redirect:/main";
        }catch (UnknownAccountException|IncorrectCredentialsException e){
            model.addAttribute("msg","用户名或密码错误！");
            return "index";
        }
    }

    @ApiOperation("注销接口")
    @GetMapping("/loginOut")
    public String logOut(){
        return "redirect:/";
    }

    @GetMapping("/user/userPage")
    public String toUserPage(){

        return "/user/userPage";
    }

}
